package main.cn.web;

import main.cn.pojo.Car;
import main.cn.service.CarService;
import main.cn.service.impl.CarServiceImpl;
import main.cn.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet(urlPatterns = "/client/carServlet")
public class CarServlet extends BaseServlet{

    private CarService carService = new CarServiceImpl();



    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Car car = WebUtils.copyParamToBean(req.getParameterMap(), new Car());
        carService.addCar(car);
        resp.sendRedirect(req.getContextPath() + "/client/carServlet?action=list");
    }

    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println(req.getParameter("id"));
        int cid = WebUtils.parseInt(req.getParameter("id"),0);
//        2、调用CarService.deleteCar();删除
        carService.deleteCarById(cid);
        resp.sendRedirect(req.getContextPath() + "/client/carServlet?action=list");
    }

    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Car car = WebUtils.copyParamToBean(req.getParameterMap(), new Car());
        carService.updateCar(car);
        resp.sendRedirect(req.getContextPath() + "/client/carServlet?action=list");
    }
    protected void getCar(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int vid = WebUtils.parseInt(req.getParameter("id"),0);
        Car car = carService.queryCarById(vid);
        req.setAttribute("cars",car);
        req.getRequestDispatcher("/page/edit/car_edit.jsp").forward(req,resp);
    }

    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List<Car> cars = carService.queryCars();

        req.setAttribute("cars",cars);

        req.getRequestDispatcher("/page/client/car.jsp").forward(req,resp);
    }
}
